package com.linkai.jacklinmap.Activity.Community;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.view.ViewCompat;

import android.Manifest;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;

import com.linkai.jacklinmap.Activity.HomeActivity;
import com.linkai.jacklinmap.Database.MyHelper;
import com.linkai.jacklinmap.R;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

/**
 * 创建日期：2021/6/13 14:52
 *
 * @author 林凯
 * 文件名称： ShareActivity.java
 * 类说明：发布动态的 Activity
 */
public class ShareActivity extends AppCompatActivity implements View.OnClickListener {

    ImageView share_back, share_album, share_camera;
    Button share_send;
    EditText et_title, et_content;
    Spinner spinner;

    // 存放图片的 LinearLayout
    LinearLayout layout_01, layout_02;
    ImageView tempImageView;        // 用来存放图片的 ImageView
    // 存放图片转换成 byte 数组的 list
    ArrayList<byte []> imageByteList;

    int imagesCount = 0;        // 记录当前总共添加了多少张图片（方便添加图片到布局中，最多添加9张图片）

    private static final int TAKE_PHOTO = 1;

    public static final int CHOOSE_PHOTO = 2;

    String title, content, privacy;

    // 数据库相关操作
    SQLiteDatabase db;
    MyHelper dbHelper;
    ContentValues values;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share);

        dbHelper = new MyHelper(ShareActivity.this);

        initWidget();

        // 设置有颜色的状态栏
        setStatusBarColor(this, Color.parseColor("#1292d0"));
    }

    private void initWidget() {
        share_back = findViewById(R.id.share_back);
        share_send = findViewById(R.id.share_send);
        share_album = findViewById(R.id.share_album);
        share_camera = findViewById(R.id.share_camera);
        spinner = findViewById(R.id.share_spinner);
        et_title = findViewById(R.id.share_et_title);
        et_content = findViewById(R.id.share_et_content);

        // 存放图片的布局初始化
        layout_01 = findViewById(R.id.share_layout_01);
        layout_02 = findViewById(R.id.share_layout_02);

        share_send.setOnClickListener(this::onClick);
        share_back.setOnClickListener(this::onClick);
        share_album.setOnClickListener(this::onClick);
        share_camera.setOnClickListener(this::onClick);

        imageByteList = new ArrayList<>();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.share_send: {
                title = et_title.getText().toString();
                content = et_content.getText().toString();
                privacy = spinner.getSelectedItem().toString();

                // 获取数据，显示用户名，注意 key 的值要和 LoginActivity 存入时 key 的值一直
                SharedPreferences mSharedPreferences = this.getSharedPreferences("userinfo", Context.MODE_PRIVATE);
                final String u_id = mSharedPreferences.getString("u_id", "");


                // 进行数据库操作
                db = dbHelper.getWritableDatabase();

                // 1. 插入数据到 Dynamic 表中
                values = new ContentValues();

                Date date = new Date();
                long datetime = date.getTime();

                // 这里要和数据库中字段对应
                values.put("u_id", u_id);
                values.put("title", title);
                values.put("content", content);
                values.put("privacy", privacy);
                values.put("c_time", datetime);
                db.insert("dynamic", null, values);

                // 1.1 插入一条动态记录之后，马上获取该记录的主键 id，方便后面将图片存入数据库中
                Cursor cursor = db.rawQuery("select last_insert_rowid() from dynamic", null);
                String d_id = null;
                if (cursor.moveToFirst()) {
                    d_id = cursor.getString(0);
                }

                // 2. 插入数据到 images 表中, images 表中一条记录就是1张图片
                ContentValues valuesImages;
                for (byte[] tempByte:imageByteList
                     ) {
                    valuesImages = new ContentValues();
                    valuesImages = new ContentValues();
                    valuesImages.put("d_id", d_id);
                    valuesImages.put("u_id", "-1");     // 属于动态的图片，不属于头像，所以 u_id 要置为 -1
                    valuesImages.put("bitmap", tempByte);
                    db.insert("images", null, valuesImages);
                }


                db.close();

                Toast.makeText(getApplicationContext(), "发布成功", Toast.LENGTH_SHORT).show();

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //do something
                        startActivity(new Intent(ShareActivity.this, HomeActivity.class));
                        // 销毁当前活动
                        finish();
                    }
                }, 1000);    //延时1s执行

                break;
            }
            case R.id.share_back: {
                finish();
                break;
            }
            case R.id.share_album: {
                if (imagesCount == 8) {
                    Toast.makeText(getApplicationContext(), "最多添加8张图片", Toast.LENGTH_SHORT).show();
                    break;
                }

                // 打开手机相册选择一张图片
                if (ContextCompat.checkSelfPermission(ShareActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(ShareActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                } else {
                    Intent intent = new Intent("android.intent.action.GET_CONTENT");
                    intent.setType("image/*");
                    startActivityForResult(intent, CHOOSE_PHOTO);       //打开相册
                }
                break;
            }
            case R.id.share_camera: {
                if (imagesCount == 8) {
                    Toast.makeText(getApplicationContext(), "最多添加8张图片", Toast.LENGTH_SHORT).show();
                    break;
                }

                // 请求权限
                if (ContextCompat.checkSelfPermission(ShareActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(ShareActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                } else {
                    //启动相机程序
                    System.out.println("启动");
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(intent, ShareActivity.TAKE_PHOTO);
                }
            }
        }
    }

    // 调用摄像头拍照或者从相册选择图片后，会自动调用这个方法，在这里面处理逻辑
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PHOTO: {
                // 拍摄照片
                // 拍照之后返回的结果
                if (resultCode == Activity.RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    Bitmap bitmap = (Bitmap) bundle.get("data");
                    mySetImageView(bitmap);
                }

                break;
            }
            case CHOOSE_PHOTO: {
                // 从相册选择照片
                Uri mImageCaptureUri = data.getData();
                if (mImageCaptureUri != null) {
                    //这个方法是根据Uri获取Bitmap图片的静态方法
                    Bitmap bitmap = null;
                    try {
                        bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), mImageCaptureUri);
                        mySetImageView(bitmap);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                break;
            }
        }
    }

    // 生成一个 ImageView 并设置到布局中
    public void mySetImageView(Bitmap bitmap) {
        // 创建一个临时的 ImageView，并添加到 LinearLayout
        int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());
        int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 75, getResources().getDisplayMetrics());

        tempImageView = new ImageView(this);
        tempImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

        LinearLayout.LayoutParams layoutParams =  new LinearLayout.LayoutParams(width, height);
        int margin1 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, getResources().getDisplayMetrics());
        int margin2 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics());
        int margin3 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, getResources().getDisplayMetrics());
        layoutParams.setMargins(margin1, margin2, margin3, 0);

        tempImageView.setLayoutParams(layoutParams);

        // 设置图片内容
        tempImageView.setImageBitmap(bitmap);
        // 同时将该图片转换为 byte数组临时保存起来
        imageByteList.add(getIconData(bitmap));

        // 图片数量加1
        imagesCount++;

        if (imagesCount <= 4) {
            layout_01.addView(tempImageView);
        } else if (imagesCount > 4 && imagesCount <= 8) {
            layout_02.addView(tempImageView);
        }
    }

    // 将 bitmap 转换成 byte[] 数组
    private byte[] getIconData(Bitmap bitmap){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    // 绘制状态栏透明
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    static void setStatusBarColor(Activity activity, int statusColor) {
        Window window = activity.getWindow();
        //取消状态栏透明
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //添加Flag把状态栏设为可绘制模式
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        //设置状态栏颜色
        window.setStatusBarColor(statusColor);
        //设置系统状态栏处于可见状态
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
        //让view不根据系统窗口来调整自己的布局
        ViewGroup mContentView = (ViewGroup) window.findViewById(Window.ID_ANDROID_CONTENT);
        View mChildView = mContentView.getChildAt(0);
        if (mChildView != null) {
            ViewCompat.setFitsSystemWindows(mChildView, false);
            ViewCompat.requestApplyInsets(mChildView);
        }
    }

}